from typing import Dict,Any,List
from ..judger import get_problem_path,get_problem_meta
import os,shutil
from pathlib import Path
import json
def prepare_workspace(worker_id:int):
    WORKSPACE=Path(__file__).parent.resolve()/"workspace"/f"ws_{worker_id}/"
    if WORKSPACE.exists():
        shutil.rmtree(WORKSPACE)
    WORKSPACE.mkdir()
    return WORKSPACE

def get_testcase_meta(problem_path,case_name):
    file:Path=problem_path/case_name/"meta.json"
    fp=file.open()
    return json.loads(fp.read())


def judge(worker_id:int,data:Dict[str,Any]):
    WORKSPACE=prepare_workspace(worker_id)
    PROBLEM=get_problem_path(data["problem"])
    pmeta=get_problem_meta(data["problem"])
    print(f"Judging {data["submission_id"]} problem {data['problem']}")
    print(f"Total case: {pmeta["data_count"]}")
    print(f"The problem type is <{pmeta["type"]}>")
    ans={}
    result={}
    result["detail"]={}
    for i in data["body"]["answer"]:
        ans[i["case"]]=i["data"]
        print(f"PA ANS {i["data"]} FOR {i["case"]}")
    for i in pmeta["data"]:
        print(f"Testing {i}")
        case_res={}
        if i not in ans:
            print(f"Answer for {i} is not found.")
            case_res["status"]="WA"
            case_res["score"]=0
            case_res["msg"]="Your answer is not found."
            result["detail"][i]=case_res
            continue
        tmeta=get_testcase_meta(PROBLEM,i)
        print("TMT ",tmeta)
        file_p:Path=WORKSPACE/"pa.txt"
        file_j:Path=PROBLEM/i/tmeta["answer"]
        fp=file_p.open("w")
        fp.write(ans[i])
        fp.close()
        ret=os.system(f"fc {file_p.resolve()} {file_j.resolve()}")
        if ret!=0:
            print(f"Wrong answer {ret}")
            case_res["status"]="WA"
            case_res["score"]=0
            case_res["msg"]=f"fc quited with exit code {ret}"
            result["detail"][i]=case_res
        else:
            print(f"Accepted {ret}")
            case_res["status"]="AC"
            case_res["score"]=tmeta["points"]
            case_res["msg"]=f"OK"
            result["detail"][i]=case_res
    result['status']="AC"
    result['score']=0
    for i in pmeta["data"]:
        if i not in result['detail']:
            result["status"]="UAC"
        else:
            if result['detail'][i]['status']!="AC":
                result["status"]="UAC"
            result['score']+=result['detail'][i]['score']
    return result

from multiprocessing import Queue,Process,Pool,Manager
import sys
def worker(worker_id:int,current_work:Dict[int,int],pending:Queue,result:Queue,task_data:Dict[int,Any]):
    print(f"Working #{worker_id} started.")
    sys.stdout.flush()
    if worker_id in current_work:
        del current_work[worker_id]
    while True:
        try:
            rid=pending.get()
        except:
            print("Quiting")
            return
        current_work[worker_id]=rid
        res=judge(worker_id,task_data[rid])
        res["submission_id"]=rid
        result.put(res)
        del task_data[rid]
        del current_work[worker_id]